package web.controller.common;

import common.consts.Actions;
import common.consts.CaptchaUsage;
import common.consts.ContentType;
import common.validation.ValidationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.AccountService;
import service.CaptchaService;
import service.ServiceResponse;
import web.Routes;
import web.controller.Base;
import web.req.PasswordRequest;

/**
 * Created by aceyin on 15/6/23.
 * <p>
 * Reset password.
 */
@RestController
@RequestMapping(Routes.Common.PASSWORD)
public class Password extends Base {

    @Autowired
    private AccountService accountService;
    @Autowired
    private CaptchaService captchaService;

    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse changeOrReset(@RequestBody PasswordRequest request) {
        ValidationResult result = request.validate();
        if (result.isFailed()) {
            return fail(result.getMessage());
        }

        String action = request.getAction();
        if (Actions.Password.RESET.name().equalsIgnoreCase(action)) {
            ServiceResponse serviceResponse = captchaService.validate(request.getMobile(), CaptchaUsage.RESET_PWD.name(), request.getToken(), request.getCaptcha());
            if (serviceResponse.isFailed()) {
                return serviceResponse;
            }

            return accountService.resetPassword(request.getMobile(), request.getPassword());
        }

        long user = getUserIdFromAuthHeader();
        return accountService.changePassword(user, request.getOpassword(), request.getPassword());
    }
}
